package com.dh.order.controller;

import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dh.order.VO.ResultVO;
import com.dh.order.common.OrderForm;
import com.dh.order.converter.OrderForm2OrderDTOConverter;
import com.dh.order.dto.OrderDTO;
import com.dh.order.enums.ResultEnum;
import com.dh.order.exception.OrderException;
import com.dh.order.service.OrderService;
import com.dh.order.utils.ResultVOUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author 作者 dinghao
 * @version 创建时间：2018年11月14日 下午3:26:08
 * @Description 类说明:
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

	@Autowired
	private OrderService orderService;

	/**
	 * 1. 参数检验 2. 查询商品信息(调用商品服务) 3. 计算总价 4. 扣库存(调用商品服务) 5. 订单入库
	 */
	@PostMapping("/create")
	public ResultVO<Object> create(@Valid OrderForm orderForm, BindingResult bindingResult) {
		// 1. 参数检验
		if (bindingResult.hasErrors()) {
			log.error("【创建订单】参数不正确, orderForm={}", orderForm);
			throw new OrderException(ResultEnum.PARAM_ERROR.getCode(),
					bindingResult.getFieldError().getDefaultMessage());
		}
		// orderForm -> orderDTO
		OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
		if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
			log.error("【创建订单】购物车信息为空");
			throw new OrderException(ResultEnum.CART_EMPTY);
		}
		// 2....5
		OrderDTO result = orderService.create(orderDTO);

		Map<String, String> map = new HashMap<>();
		map.put("orderId", result.getOrderId());
		return ResultVOUtil.success(map);
	}

	/**
	 * 
	 * @Title: finish
	 * @author dinghao
	 * @Description: 完结订单
	 * @param orderId
	 * @return ResultVO<Object>
	 */
	@PostMapping("/finish")
	public ResultVO<Object> finish(@RequestParam("orderId") String orderId) {
		return ResultVOUtil.success(orderService.finish(orderId));
	}
}
